var User = {
	inputForm		: null,		//录入表单
	inputWindow		: null,		//录入对话框
	fieldAnchor		: Common.config.fieldAnchor,
	windowWidth 	: document.body.clientWidth > 660 ? 660 : document.body.clientWidth - 10,
	windowHeight 	: document.body.clientHeight > 266 ? 266 : document.body.clientHeight - 10,
	optype			: null,
	getInputForm	: function () {
		if (this.inputForm != null) {
			return this.inputForm;
		}
		this.inputForm = new Ext.FormPanel({
			id: 'inputForm',
			region: 'center',
			bodyStyle: 'padding:5px; overflow-x:visible;overflow-y:scroll',
			autoScroll: true,
			border    : false,
	        frame: false,
	        labelAlign: 'right',
	        labelWidth: 86,	        
         	items: [{
        		xtype: 'panel',
        		//title: '基本信息',
        		autoHeight: true,
        		border: false,
            	items: [{
	            	layout: 'column',border: false, labelSeparator: ':',
	                defaults:{layout: 'form', border: false, columnWidth: 0.5},
	                items: [{
	                	xtype: 'panel',
	                	id: 'useridPanel',
	                	items:[{
	                		xtype: 'hidden', id: 'userId', name: 'user.userId'
	                	},{
	                		xtype: 'hidden', id: 'user.password', name: 'user.password'
	                	},{
	                		xtype: 'textfield', id: 'loginId', name: 'user.loginId', anchor: this.fieldAnchor,
	                		fieldLabel: Common.config.redStar + '登录名', readOnly: false, allowBlank: false
	                	}]
	                },{
	                	items:[{
	                		xtype: 'textfield', id: 'userName', name: 'user.userName', anchor: this.fieldAnchor,
	                		fieldLabel: Common.config.redStar + '姓名', readOnly: false, allowBlank: false
	                	}]
	                },{
	                	items:[{
	                		xtype: 'combo', id: 'userSex', hiddenName: 'user.userSex', anchor: this.fieldAnchor,
	                		fieldLabel: Common.config.redStar + '用户性别', readOnly: false, allowBlank: false,
			                mode: 'local', triggerAction: 'all', valueField: 'value', displayField: 'text',
			                readOnly: false, resizable: true, value: 0,
			                store: new Ext.data.SimpleStore({
								fields: ['value', 'text'], data: DataDict.sexArray
							})
	                	}]
	                },{
	                	items:[{
	                		xtype: 'combo', id: 'isavailability', hiddenName: 'user.isavailability', anchor: this.fieldAnchor,
	                		fieldLabel: Common.config.redStar + '用户状态', readOnly: false, allowBlank: false,
			                mode: 'local', triggerAction: 'all', valueField: 'value', displayField: 'text',
			                readOnly: false, resizable: true, value: 1,
			                store: new Ext.data.SimpleStore({
								fields: ['value', 'text'], data: DataDict.statusArray
							})
	                	}]
	                },{
	                	items:[{
	                		xtype: 'textfield', id: 'mobilePhone', name: 'user.mobilePhone', anchor: this.fieldAnchor,
	                		fieldLabel: '联系电话', readOnly: false, allowBlank: true
	                	}]
	                },{
	                	items:[ {
	                		xtype: 'textfield', inputType: 'password', id: 'newpwd', name: 'newpwd', anchor: this.fieldAnchor,
	                		fieldLabel: '密码', readOnly: false, allowBlank: true
	                	}]
	                },{
	                	items:[{
	                		xtype: 'textfield', id: 'mailAddr', name: 'user.mailAddr', vtype: 'email', anchor: this.fieldAnchor,
	                		fieldLabel: '邮箱地址', readOnly: false, allowBlank: true
	                	}]
	                },{
	                	items:[{
	                		xtype: 'textfield', inputType: 'password', id: 'newpwdconfirm', name: 'newpwdconfirm', anchor: this.fieldAnchor,
	                		fieldLabel: '密码确认', readOnly: false, allowBlank: true, vtype:'password', vtypeText:'两次密码不一致', confirmTo:'newpwd'
	                	}]
	                },{
	                	items:[{
	                		xtype: 'datefield', id: 'effectdateend', name: 'user.effectdateend', anchor: this.fieldAnchor,
	                		fieldLabel: '失效日期', readOnly: false, allowBlank: true, format: 'Y-m-d'
	                	}]
	                }, {
	                	columnWidth: 1.0,
	                	items:[{
	                		xtype: 'lovcombo', id: 'user.roleids', hiddenName: 'roleids', anchor: '97.1%',
	                		fieldLabel: '用户角色', readOnly: false, allowBlank: true,
	                		triggerAction: 'all', resizable: true, lazyInit: true, 
	                		store: Role.getRoleStore(),
			                mode: 'remote',
			                triggerAction: 'all',
			                valueField: 'roleId',
			                displayField: 'roleName'
	                	}]
	                }]
            	}]
         	}]
		});
		return this.inputForm;
	},
	showInputWindow : function (title) {
		if (this.inputWindow == null) {
			var inputForm = User.getInputForm();
			this.inputWindow = new Ext.Window({ //定义对话框
				title: '用户信息录入',
				closeAction : 'hide',
				modal : true,
				shadow : true,
				closable : true,
				plain    : true,
				layout : 'fit',
				width : this.windowWidth,
				height : this.windowHeight,
				items:[inputForm],
				buttons : [{
					text :'保存',
					iconCls: 'icon_save',
					scope: this,
					handler: this.onSaveUser
				},{
					text :'关闭',
					iconCls: 'icon_close',
					scope: this,
					handler: function(){ this.inputWindow.hide();}
				}]
			});
			/**
            Role.roleStore.addListener("load", function (thisStore, records, options) {
		   		Role.initUserRole();
			});
            Role.loadRoleStore();	//初始化角色信息
            */
		}
		this.inputWindow.show();
		this.inputWindow.setTitle(title || "用户信息录入");
	},
	onSaveUser : function () {
		var thisForm = User.getInputForm().getForm();
		if (!thisForm.isValid()) {
			return;
		}
		var newpwd 				= thisForm.findField("newpwd");
		var newpwdconfirmCmp 	= thisForm.findField("newpwdconfirm");
		if (newpwd.getValue() != newpwdconfirmCmp.getValue()) {
			newpwdconfirmCmp.markInvalid("密码确认与新输入的密码不一致!");
			return;
		}
		if (!Ext.isEmpty(thisForm.findField('loginId').getValue())) {
			thisForm.findField('loginId').setValue(thisForm.findField('loginId').getValue().toLowerCase());
		}
		var url = "";
		if (User.optype == Common.optype.add) {
			if (newpwd.getValue() == "") {
				newpwd.setValue("123456");
			}
			thisForm.findField("user.password").setValue(newpwd.getValue());
			url = sys.basePath + "systemuser/addUser.do";
		} else {
			url = sys.basePath + "systemuser/updateUser.do";
		}
		Common.showProcessMsgBox("信息保存中，请稍后...");
		thisForm.submit({
			url: url,
            success: function(form, action){
            	Common.hideProcessMsgBox();
                Ext.topShow.msg('成功提示', action.result.msg);
                User.inputWindow.hide();
                dataGrid.getStore().reload();
            },
            failure : function (form, action) {
            	Common.hideProcessMsgBox();
            	var failMsg = Ext.isEmpty(action.result) ? "用户信息保存失败." : action.result.msg;
        	 	Ext.Msg.show({
   	                title: '失败提示',
   	                msg: failMsg || '用户信息保存失败.',
   	                width: 180,
   	                modal: false,
   	                buttons : Ext.Msg.OK,
   	                icon: Ext.MessageBox.ERROR
   	            });
            }
        });
	},
	onAdd : function () {		//新增
		User.optype	= Common.optype.add;
		User.showInputWindow("新增用户");
		Ext.getCmp('useridPanel').show();
		User.getInputForm().doLayout(true);
		User.getInputForm().getForm().reset();
	},
	onUpdate : function () {	//修改
		if (dataGrid.getSelectionModel().getCount() != 1) {
            Ext.Msg.alert("提示信息", "请选择一条记录!");
            return;
        }
		User.optype	= Common.optype.update;
		var selectedRecord = dataGrid.getSelectionModel().getSelected();
		/**
        Role.userid = selectedRecord.get("userid");
		if (User.inputWindow != null && Role.getRoleStore().getCount() > 0) {
			Role.initUserRole();
		}
		*/
		User.showInputWindow("修改用户信息");
		Ext.getCmp('useridPanel').hide();
		User.getInputForm().doLayout(true);
		Common.showProcessMsgBox('表单数据初始化中，请稍后...');
		var thisForm = User.getInputForm().getForm();
		thisForm.reset();
		var values = {
			userId			:	selectedRecord.get("userId"),				userName		:	selectedRecord.get("userName"),
			mobilePhone		:	selectedRecord.get("mobilePhone"),			mailAddr		:	selectedRecord.get("mailAddr"),		
			userSex			:	selectedRecord.get("userSex"),				isavailability	:	selectedRecord.get("isavailability"),		
			loginId			:	selectedRecord.get("loginId"),				
			effectdateend	: 	Common.renderer.dateRender(selectedRecord.get("effectdateend"))
		};
		thisForm.setValues(values);
		Role.initUserRole(values.userId);
	},
	onDelete : function () {	//删除用户
		var selectedRecordArray = dataGrid.getSelectionModel().getSelections();
		if(selectedRecordArray.length < 1){
     		Ext.Msg.alert("提示信息", "请选择要删除的记录!");
     		return;
      	}
		User.optype	= Common.optype.del;
        Ext.Msg.confirm("确认提示", "确定删除选定的记录?", function(btn){
         	if(btn == 'yes'){
              	var userids = "";
              	for(var i = 0;i < selectedRecordArray.length;i++){
              		userids += selectedRecordArray[i].get("userId") + ",";
        	    }
        	    if(userids.length > 0){
        	    	userids = userids.substring(0, userids.length - 1);
        	    }
				Common.showProcessMsgBox('数据删除中，请稍后...');
				Ext.Ajax.request({
					method:'POST', 
					timeout:0,
					url : sys.basePath + 'systemuser/deleteUser.do',
					params : {
						userIds : userids
					},
					success : function(response, options) {
						var result = Ext.util.JSON.decode(response.responseText);
						Ext.MessageBox.hide();
						if (result.success) {
					 		Ext.topShow.msg("成功提示", result.msg);
					 		dataGrid.getStore().reload();
		   			   	} else {
		   			   		Ext.Msg.show({
		       	                title: '失败提示',
		       	                msg: result.msg,
		       	                width: 180,
		       	                modal: false,
		       	                buttons : Ext.Msg.OK,
		       	                icon: Ext.MessageBox.ERROR
		       	            });
		       			}
					},
					failure : function() {
						Ext.MessageBox.hide();
		   			   	Ext.Msg.show({
		   	                title: '失败提示',
		   	                msg: '删除数据时发生异常.',
		   	                width: 180,
		   	                modal: false,
		   	                buttons : Ext.Msg.OK,
		   	                icon: Ext.MessageBox.ERROR
		   	            });
					}
				});
         	}
        });	
	},
	/**
	 * 启用
	 */
	enable : function () {
		var selectedRecordArray = dataGrid.getSelectionModel().getSelections();
		if(selectedRecordArray.length < 1){
     		Ext.Msg.alert("提示信息", "请选择需启用的用户记录!");
     		return;
      	}
		var userids = "";
      	for(var i = 0;i < selectedRecordArray.length;i++){
      		userids += selectedRecordArray[i].get("userId") + ",";
	    }
	    if(userids.length > 0){
	    	userids = userids.substring(0, userids.length - 1);
	    }
		Common.ajaxRequest({
			url: sys.basePath + 'systemuser/enableUser.do', params: {userIds: userids},
			proccessMsg: '用户启用处理中, 请稍后...', successHandler: function () {dataGrid.getStore().reload();}
		});
	},
	/**
	 * 禁用
	 */
	disable : function () {
		var selectedRecordArray = dataGrid.getSelectionModel().getSelections();
		if(selectedRecordArray.length < 1){
     		Ext.Msg.alert("提示信息", "请选择需启用的用户记录!");
     		return;
      	}
		var userids = "";
      	for(var i = 0;i < selectedRecordArray.length;i++){
      		userids += selectedRecordArray[i].get("userId") + ",";
	    }
	    if(userids.length > 0){
	    	userids = userids.substring(0, userids.length - 1);
	    }
		Common.ajaxRequest({
			url: sys.basePath + 'systemuser/disableUser.do', params: {userIds: userids},
			proccessMsg: '用户禁用处理中, 请稍后...', successHandler: function () {dataGrid.getStore().reload();}
		});
	}
};

var Role = {
	userid 				: null,
	roleStore 			: null
};
Role = {
	getRoleStore : function () { 
		if (this.roleStore == null) {
			this.roleStore = new Ext.data.Store({
				url: sys.basePath + 'systemrole/findRole.do?limit=-1&ifPage=false',
				autoLoad : false, remoteSort: false,
				reader: new Ext.data.JsonReader({
					id: 'roleId'
				},
				Ext.data.Record.create([
		       		{name: 'roleId', type: 'string', mapping: 'userroleId'},
		       		{name: 'roleName', type: 'string', mapping: 'userroleName'}
				]))
			});
		}
		return this.roleStore;
	},
	initUserRole : function (userid) {
		Role.userid = userid;
		if (Role.userid == null) {
			return;
		}
		this.roleStore.addListener('load', function (thisStore, records, options) {
			if (records == null || records.length == 0) {
				return;
			}
			Role.queryUserRoles(Role.userid);
		});
		if (Role.getRoleStore().getCount() > 0) {
			Role.queryUserRoles(Role.userid);
		} else {
			this.loadRoleStore();
		}
	},
	queryUserRoles : function (userid) {
		//初始化用户所属用户组信息
		Ext.Ajax.request({
			method:'POST', 
			timeout:0,
			url : sys.basePath + 'systemuser/findRoleByUser.do',
			params : {userId : userid},
			success : function(response, options) {
				Ext.MessageBox.hide();
				var roleArray = Ext.util.JSON.decode(response.responseText);
				if (roleArray == null || roleArray.length == 0) {
					return;
				}
				var roleids = '';
				for (var i = 0; i < roleArray.length; i++) {
					roleids += roleArray[i].userroleId;
					if ((i + 1) < roleArray.length) {
						roleids += ',';
					}
				}
				Ext.getCmp('user.roleids').setValue(roleids);
			},
			failure : function() {
				Ext.MessageBox.hide();
   			   	Ext.Msg.show({
   	                title: '失败提示',
   	                msg: '初始化用户所属用户组信息时发生异常.',
   	                width: 180,
   	                modal: false,
   	                buttons : Ext.Msg.OK,
   	                icon: Ext.MessageBox.ERROR
   	            });
			}
		});
	},
	loadRoleStore : function () {
		Role.getRoleStore().load();
	}
};

//自定义password验证函数
Ext.apply(Ext.form.VTypes,{
    password:function(val,field){
       if(field.confirmTo){
           var pwd=Ext.get(field.confirmTo);
           return (val==pwd.getValue());
       }
       return true;
    }
});